package com.mmr.dxp.job;

import com.alibaba.fastjson2.JSONObject;
import com.mmr.dxp.domain.*;
import com.mmr.dxp.mapper.DataTobePushedMapper;
import com.mmr.dxp.mapper.ExchangeDataLogMapper;
import com.mmr.dxp.mapper.RdsSourceSubMapper;
import com.mmr.dxp.service.DxpBlockChainSupportService;
import com.mmr.util.ApplicationContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Component
@Configurable
@EnableScheduling
@ConditionalOnProperty(prefix = "api", name = "enable", havingValue = "true")
public class DxpScheduledJobs {
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    @Resource
    private ExchangeDataLogMapper exchangeLogMapper;
    @Resource
    private RdsSourceSubMapper rdsSourceSubMapper;
    @Resource
    private DxpBlockChainSupportService dxpBlockChainSupportService;
    @Resource
    DataTobePushedMapper dataTobePushedMapper;

    /**
     * DXP交换系统资源交换记录上链接口
     */
    //@Scheduled(cron = " 0 0 1 * * ? ")
    @Scheduled(cron = "0 */5 * * * ?")
    public void dxpResourceExchangeRecordUpload() {
        String lastDay = getLastDay();
        List<ExchangeDataLog> dataLogList = exchangeLogMapper.listExchangeDataLog(lastDay);
        JSONObject dataJsonObj = new JSONObject();
        dataLogList.stream().forEach(datalog -> {
            String subId = datalog.getSubId();
            RdsSourceSub rdsSourceSub = rdsSourceSubMapper.selectByPrimaryKey(subId);
            RdsResourceObject rdsResourceObject = rdsSourceSub.getResource();
            Assert.notNull(rdsResourceObject, "订阅资源不能为空");
            String resourceName = rdsResourceObject.getName();
            String resourceId = rdsResourceObject.getId();
            String cataId = rdsResourceObject.getCataId();
            String cataTitle = rdsResourceObject.getCataTitle();
            dataJsonObj.put("resourceId", resourceId);
            dataJsonObj.put("resourceName", resourceName);
            dataJsonObj.put("cataId", cataId);
            dataJsonObj.put("cataTitle", cataTitle);
            OrganInfo org = rdsSourceSub.getOrganInfo();
            String subOrgName = org.getName();
            dataJsonObj.put("subscriber", subOrgName);
            long sendNum = datalog.getSendSum();
            long rcvNum = datalog.getRcvSum();
            dataJsonObj.put("dataSendNum", sendNum);
            dataJsonObj.put("dataReceiveNum", rcvNum);
            String startTime = datalog.getExchangeDate();
            String overTime = datalog.getOperateDate();
            dataJsonObj.put("startTime", startTime);
            dataJsonObj.put("overTime", overTime);
            String dataJsonStr = dataJsonObj.toJSONString();
            dxpBlockChainSupportService.dxpResourceExchangeRecordUpload(dataJsonStr);
        });
    }
    /**
     * 每5分钟重发发送失败的消息
     */
    @Async
    @Scheduled(cron = "0 */5 * * * ?")
    public void resendMessage() {
        log.info("定时处理发送失败的消息任务开始");
        List<DataTobePushed> dataTobePushedList = dataTobePushedMapper.listByLimit(50);
        log.info("需要重发的消息共{}条",dataTobePushedList.size());
        dataTobePushedList.forEach(data -> {
            try {
                Class[] classes = ApplicationContextUtil.getClass(String.class);
                ApplicationContextUtil.getMethod(data.getClassName(), data.getMethodName(), classes, data.getReqBody());
                dataTobePushedMapper.deleteById(data.getId());
            } catch (Exception e) {
                log.error("定时处理发送失败的消息任务失败：{}",e.getMessage());
            }
        });
    }
    /**
     * 获取前一天的日期
     *
     * @return
     */
    public String getLastDay() {
        Calendar calendar = new GregorianCalendar();
        calendar.add(Calendar.DATE, -1);
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return sdf.format(calendar.getTime());
    }
    /**
     * 获取前一天的开始时间和结束时间
     *
     * @return
     */
    public Map<String, String> getLastDay() {
        Map<String, String> lastHour = new HashMap<>();
        Calendar calendar = new GregorianCalendar();
        calendar.add(Calendar.DATE, -1);
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        lastHour.put("start", sdf.format(calendar.getTime()));
        calendar.set(Calendar.HOUR, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        lastHour.put("end", sdf.format(calendar.getTime()));
        return lastHour;
    }
}